package org.phalanx.client.net;

import java.io.IOException;
import java.util.Date;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.phalanx.client.PhalanxClient;
import org.phalanx.messenging.AuthenticationMessage;
import org.phalanx.messenging.PingTimeMessage;
import org.phalanx.messenging.management.MessageListener;
import org.phalanx.messenging.management.MessageManager;
import org.phalanx.messenging.management.PhalanxMetaMessage;

public class PhalanxConnectionManager {
	private boolean connectionState;
	private MessageManager msgMgr;
	private PhalanxConnectionListener listener;
	private AuthenticationManager authenticationMgr;
	private String serverNode;
	KeepAliveThread keepAlive;
	public static long TIME_OUT = 15000L;
	
	public PhalanxConnectionManager(String pServer) {
		this.serverNode = pServer;
		msgMgr = new MessageManager();
		authenticationMgr = new AuthenticationManager(this);
		keepAlive = new KeepAliveThread(this);
		setConnectionState(false);
	}
	
	public PhalanxConnectionManager() {
		setConnectionState(false);
		authenticationMgr = new AuthenticationManager(this);
		msgMgr = new MessageManager();
	}
	
	public void setConnectionState(boolean state) {
		connectionState = state;
		
		if (state == false && keepAlive != null) {
			keepAlive.setThreadState(false);
		}
	}
	
	public void setServerNode(String node) {
		if (connectionState) {
			setConnectionState(false);
		}
		
		serverNode = node;
	}
	
	public void connectToServerNode() throws IOException{
		ChatManager c = PhalanxClient.getClientInstance().getXMPPConnectionManager().getChatManager();
		keepAlive = new KeepAliveThread(this);
		if (connectionState) {
			setConnectionState(false);
		}
		
		if (serverNode != null) {
			listener = new PhalanxConnectionListener(serverNode, msgMgr);
			c.addChatListener(listener);
			msgMgr.addMessageListener(new AuthenticationMessage(), authenticationMgr);
			msgMgr.addMessageListener(new PingTimeMessage(), keepAlive);
			authenticationMgr.logIn(serverNode);
			
			int i = 0;

			try {
				do {
					i++;
					Thread.sleep(10);
					if (authenticationMgr.getState() == AuthenticationManager.CONNECTED) {
						i = 10000;
					}
				}while(i < 1000);
				if (i != 10000) {
					setConnectionState(false);
					throw new IOException();
				}
				setConnectionState(true);
				keepAlive.start();
			} catch (InterruptedException ie) {throw new IOException();}
		}
	}
	
	public String getServerNode() {
		return serverNode;
	}
	
	public MessageManager getMessageManager() {
		return msgMgr;
	}
	
	public Chat createChatObject(String uID) {
		return PhalanxClient.getClientInstance().getXMPPConnectionManager().getChatManager().createChat(uID, listener);
	}
}
